<?php

namespace App\Models;


class Notice extends BaseModel
{
    protected $table = "notice";

    protected $redisTable = "notice";

    protected $rules = [
        'admin_id' => 'required',
        'shop_id' => 'required',
        'msg' => 'between:0,80',
    ];

    protected $message = [
        'admin_id.required' => '非法操作',
        'shop_id.required' => '非法操作',
        'msg.between' => '消息字数不能超过15个字',
    ];


    public function addOrUpdate()
    {
        $data['admin_id'] = intval(request('admin_id'));
        $data['shop_id'] = intval(request('shop_id'));
        $data['msg'] = trim(request('msg'));
        $data['status'] = request('status',0);
        if (request('id')) {
            $data['id'] = trim(request('id'));
        }
        if (!$this->_validate($data)) {
            return false;
        }
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '保存失败!';
            return false;
        }
        $this->_redisGenerate($data['shop_id']);
        //记录行为
        return $res;
    }

    public function _redisGenerate($sid)
    {
        $table = $this->redisTable;
        $key = $sid;
        $this->redis->hdel($table, $key);
    }


    public function _redisGetOneBySid($sid)
    {
        $table = $this->redisTable;
        $key = $sid;
        if ($this->redis->hexists($table, $key)) {
            $res = $this->redis->hmget($table, $key);
            if ($res) {
                return unserialize($res[0]);
            }
        }
        $res = $this->_getOne(['shop_id'=>$sid]);
        if ($res) {
            $res = $res->toArray();
            $this->redis->hmset($table, [$key => serialize($res)]);
        }
        return $res;
    }

}